'use client'

import React, { useState, useEffect } from 'react'
import { 
  EmergencyEvent, 
  EmergencyType, 
  EmergencySeverity, 
  EmergencyStatus, 
  emergencyService, 
  emergencyTemplates 
} from '@/lib/emergencyEvents'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from '@/components/ui/card'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { ScrollArea } from '@/components/ui/scroll-area'
import { Separator } from '@/components/ui/separator'
import { toast } from 'sonner'
import { hospitalData } from '@/lib/realData'

interface EmergencyPanelProps {
  onEmergencySelect?: (emergency: EmergencyEvent) => void
  onEmergencyCreate?: (emergency: EmergencyEvent) => void
  className?: string
}

export const EmergencyPanel: React.FC<EmergencyPanelProps> = ({
  onEmergencySelect,
  onEmergencyCreate,
  className = ''
}) => {
  const [activeEmergencies, setActiveEmergencies] = useState<EmergencyEvent[]>([])
  const [historicalEmergencies, setHistoricalEmergencies] = useState<EmergencyEvent[]>([])
  const [selectedEmergency, setSelectedEmergency] = useState<EmergencyEvent | null>(null)
  const [demoMode, setDemoMode] = useState(false)
  const [demoInterval, setDemoInterval] = useState<NodeJS.Timeout | null>(null)

  // 初始化和加载数据
  useEffect(() => {
    // 加载已有的突发事件
    setActiveEmergencies(emergencyService.getActiveEmergencies())
    setHistoricalEmergencies(emergencyService.getHistoricalEmergencies())
    
    // 添加监听器
    const unsubscribe = emergencyService.addListener((events) => {
      setActiveEmergencies(events)
      setHistoricalEmergencies(emergencyService.getHistoricalEmergencies())
    })
    
    return () => {
      unsubscribe()
      if (demoInterval) {
        clearInterval(demoInterval)
      }
    }
  }, [demoInterval])
  
  // 处理事件选择
  const handleEmergencySelect = (emergency: EmergencyEvent) => {
    setSelectedEmergency(emergency)
    if (onEmergencySelect) {
      onEmergencySelect(emergency)
    }
  }
  
  // 创建随机突发事件（用于演示）
  const createRandomEmergency = () => {
    const emergency = emergencyService.generateRandomEmergency(hospitalData)
    if (emergency) {
      toast.info(`已创建新的突发事件: ${emergency.title}`, {
        description: emergency.description
      })
      
      if (onEmergencyCreate) {
        onEmergencyCreate(emergency)
      }
    }
  }
  
  // 创建指定类型的突发事件
  const createEmergency = (templateKey: keyof typeof emergencyTemplates) => {
    // 随机选择一个部门
    const department = hospitalData.departments[
      Math.floor(Math.random() * hospitalData.departments.length)
    ]
    
    // 生成随机坐标（基于中心点的偏移）
    const centerLat = 30.2741 // 假设的医院中心点
    const centerLng = 120.1551
    const latOffset = (Math.random() - 0.5) * 0.002 // 约±100米
    const lngOffset = (Math.random() - 0.5) * 0.002
    
    const emergency = emergencyService.createEmergency(
      templateKey,
      {
        name: department.name,
        floor: department.floor,
        coordinates: [centerLng + lngOffset, centerLat + latOffset],
        areaRadius: 20 + Math.random() * 30 // 20-50米的影响范围
      }
    )
    
    toast.info(`已创建新的突发事件: ${emergency.title}`, {
      description: emergency.description
    })
    
    if (onEmergencyCreate) {
      onEmergencyCreate(emergency)
    }
  }
  
  // 更新事件状态
  const updateEmergencyStatus = (id: string, status: EmergencyStatus, message: string) => {
    const updatedEmergency = emergencyService.updateEmergency(
      id, 
      { status }, 
      message
    )
    
    if (updatedEmergency) {
      toast.success(`已更新事件状态: ${updatedEmergency.title}`, {
        description: message
      })
      
      // 如果当前选中的是被更新的事件，更新选中状态
      if (selectedEmergency && selectedEmergency.id === id) {
        setSelectedEmergency(updatedEmergency)
      }
    }
  }
  
  // 切换演示模式
  const toggleDemoMode = () => {
    if (demoMode) {
      // 关闭演示模式
      if (demoInterval) {
        clearInterval(demoInterval)
        setDemoInterval(null)
      }
      setDemoMode(false)
      toast.info('已关闭演示模式')
    } else {
      // 开启演示模式
      setDemoMode(true)
      toast.info('已开启演示模式，系统将随机生成突发事件')
      
      // 立即创建一个事件
      createRandomEmergency()
      
      // 设置定时器，每30-90秒随机生成一个事件
      const interval = setInterval(() => {
        // 随机决定是否生成新事件
        if (Math.random() > 0.3) { // 70%的概率生成新事件
          createRandomEmergency()
        }
        
        // 模拟事件进展
        emergencyService.simulateEventProgression()
      }, 30000 + Math.random() * 60000) // 30-90秒
      
      setDemoInterval(interval)
    }
  }
  
  // 获取事件严重程度的标签样式
  const getSeverityBadge = (severity: EmergencySeverity) => {
    switch (severity) {
      case EmergencySeverity.CRITICAL:
        return <Badge variant="destructive">危急</Badge>
      case EmergencySeverity.HIGH:
        return <Badge variant="destructive" className="bg-orange-500">高危</Badge>
      case EmergencySeverity.MEDIUM:
        return <Badge variant="outline" className="border-yellow-500 text-yellow-700">中度</Badge>
      case EmergencySeverity.LOW:
        return <Badge variant="outline" className="border-blue-500 text-blue-700">低危</Badge>
      default:
        return <Badge>未知</Badge>
    }
  }
  
  // 获取事件状态的标签样式
  const getStatusBadge = (status: EmergencyStatus) => {
    switch (status) {
      case EmergencyStatus.ACTIVE:
        return <Badge variant="destructive">活跃</Badge>
      case EmergencyStatus.RESPONDING:
        return <Badge className="bg-blue-500">响应中</Badge>
      case EmergencyStatus.CONTAINED:
        return <Badge className="bg-green-500">已控制</Badge>
      case EmergencyStatus.RESOLVED:
        return <Badge variant="outline" className="border-gray-500 text-gray-700">已解决</Badge>
      default:
        return <Badge>未知</Badge>
    }
  }
  
  // 获取事件类型的图标和颜色
  const getTypeIcon = (type: EmergencyType) => {
    switch (type) {
      case EmergencyType.FIRE:
        return { icon: '🔥', color: 'text-red-500' }
      case EmergencyType.MEDICAL:
        return { icon: '🚑', color: 'text-blue-500' }
      case EmergencyType.SECURITY:
        return { icon: '🔒', color: 'text-yellow-500' }
      case EmergencyType.INFRASTRUCTURE:
        return { icon: '🔧', color: 'text-gray-500' }
      case EmergencyType.CROWD:
        return { icon: '👥', color: 'text-purple-500' }
      case EmergencyType.EXTERNAL:
        return { icon: '⚠️', color: 'text-orange-500' }
      default:
        return { icon: '❓', color: 'text-gray-500' }
    }
  }
  
  // 格式化时间
  const formatTime = (timeString: string) => {
    const date = new Date(timeString)
    return date.toLocaleString('zh-CN', {
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit',
      hour12: false
    })
  }
  
  return (
    <div className={`flex flex-col h-full ${className}`}>
      <div className="flex items-center justify-between mb-4">
        <h2 className="text-xl font-bold">突发事件管理</h2>
        <div className="flex space-x-2">
          <Button 
            variant={demoMode ? "destructive" : "default"}
            size="sm"
            onClick={toggleDemoMode}
          >
            {demoMode ? '停止演示' : '开始演示'}
          </Button>
        </div>
      </div>
      
      <Tabs defaultValue="active" className="flex-1 flex flex-col">
        <TabsList className="grid grid-cols-2">
          <TabsTrigger value="active">
            活跃事件 {activeEmergencies.length > 0 && <span className="ml-1 bg-red-500 text-white rounded-full w-5 h-5 inline-flex items-center justify-center text-xs">{activeEmergencies.length}</span>}
          </TabsTrigger>
          <TabsTrigger value="historical">历史事件</TabsTrigger>
        </TabsList>
        
        <TabsContent value="active" className="flex-1 flex flex-col">
          <div className="mb-4 grid grid-cols-2 gap-2">
            <Button 
              variant="outline" 
              size="sm"
              onClick={() => createEmergency('fire')}
              className="text-red-500 border-red-200 hover:bg-red-50"
            >
              🔥 火灾
            </Button>
            <Button 
              variant="outline" 
              size="sm"
              onClick={() => createEmergency('medicalEmergency')}
              className="text-blue-500 border-blue-200 hover:bg-blue-50"
            >
              🚑 医疗紧急
            </Button>
            <Button 
              variant="outline" 
              size="sm"
              onClick={() => createEmergency('securityBreach')}
              className="text-yellow-500 border-yellow-200 hover:bg-yellow-50"
            >
              🔒 安全事件
            </Button>
            <Button 
              variant="outline" 
              size="sm"
              onClick={() => createEmergency('powerOutage')}
              className="text-gray-500 border-gray-200 hover:bg-gray-50"
            >
              🔌 电力故障
            </Button>
          </div>
          
          <div className="flex-1 overflow-y-auto pr-4" style={{ maxHeight: '400px' }}>
            {activeEmergencies.length === 0 ? (
              <div className="flex flex-col items-center justify-center h-40 text-gray-500">
                <p>当前没有活跃的突发事件</p>
                <Button 
                  variant="ghost" 
                  size="sm"
                  onClick={createRandomEmergency}
                  className="mt-2"
                >
                  创建随机事件
                </Button>
              </div>
            ) : (
              <div className="space-y-3">
                {activeEmergencies.map(emergency => (
                  <Card 
                    key={emergency.id}
                    className={`cursor-pointer transition-all hover:shadow-md ${selectedEmergency?.id === emergency.id ? 'ring-2 ring-blue-500' : ''}`}
                    onClick={() => handleEmergencySelect(emergency)}
                  >
                    <CardHeader className="py-3">
                      <div className="flex justify-between items-start">
                        <div className="flex items-center">
                          <span className={`text-lg mr-2 ${getTypeIcon(emergency.type).color}`}>
                            {getTypeIcon(emergency.type).icon}
                          </span>
                          <CardTitle className="text-base">{emergency.title}</CardTitle>
                        </div>
                        <div className="flex space-x-1">
                          {getSeverityBadge(emergency.severity)}
                          {getStatusBadge(emergency.status)}
                        </div>
                      </div>
                      <CardDescription className="text-xs mt-1">
                        {emergency.location.name} · {emergency.location.floor} · {formatTime(emergency.startTime)}
                      </CardDescription>
                    </CardHeader>
                    <CardContent className="py-0">
                      <p className="text-sm text-gray-700">{emergency.description}</p>
                    </CardContent>
                    <CardFooter className="py-2 flex justify-between">
                      <div className="text-xs text-gray-500">
                        ID: {emergency.id}
                      </div>
                      <div className="flex space-x-1">
                        {emergency.status === EmergencyStatus.ACTIVE && (
                          <Button 
                            variant="outline" 
                            size="sm"
                            onClick={(e) => {
                              e.stopPropagation();
                              updateEmergencyStatus(
                                emergency.id, 
                                EmergencyStatus.RESPONDING, 
                                '响应团队已到达现场，开始处理'
                              );
                            }}
                          >
                            开始响应
                          </Button>
                        )}
                        {emergency.status === EmergencyStatus.RESPONDING && (
                          <Button 
                            variant="outline" 
                            size="sm"
                            onClick={(e) => {
                              e.stopPropagation();
                              updateEmergencyStatus(
                                emergency.id, 
                                EmergencyStatus.CONTAINED, 
                                '事件已被控制，正在恢复中'
                              );
                            }}
                          >
                            标记为已控制
                          </Button>
                        )}
                        {emergency.status === EmergencyStatus.CONTAINED && (
                          <Button 
                            variant="outline" 
                            size="sm"
                            onClick={(e) => {
                              e.stopPropagation();
                              updateEmergencyStatus(
                                emergency.id, 
                                EmergencyStatus.RESOLVED, 
                                '事件已解决，恢复正常运营'
                              );
                            }}
                          >
                            标记为已解决
                          </Button>
                        )}
                      </div>
                    </CardFooter>
                  </Card>
                ))}
              </div>
            )}
          </div>
        </TabsContent>
        
        <TabsContent value="historical" className="flex-1">
          <div className="h-full overflow-y-auto pr-4" style={{ maxHeight: '400px' }}>
            {historicalEmergencies.length === 0 ? (
              <div className="flex items-center justify-center h-40 text-gray-500">
                <p>没有历史事件记录</p>
              </div>
            ) : (
              <div className="space-y-3">
                {historicalEmergencies.map(emergency => (
                  <Card 
                    key={emergency.id}
                    className="opacity-80 hover:opacity-100 transition-opacity"
                    onClick={() => handleEmergencySelect(emergency)}
                  >
                    <CardHeader className="py-2">
                      <div className="flex justify-between items-start">
                        <div className="flex items-center">
                          <span className={`text-lg mr-2 ${getTypeIcon(emergency.type).color}`}>
                            {getTypeIcon(emergency.type).icon}
                          </span>
                          <CardTitle className="text-base">{emergency.title}</CardTitle>
                        </div>
                        {getStatusBadge(emergency.status)}
                      </div>
                      <CardDescription className="text-xs mt-1">
                        {emergency.location.name} · 已解决于 {formatTime(emergency.updates[emergency.updates.length - 1].timestamp)}
                      </CardDescription>
                    </CardHeader>
                  </Card>
                ))}
              </div>
            )}
          </div>
        </TabsContent>
      </Tabs>
      
      {selectedEmergency && (
        <div className="mt-4">
          <Separator className="my-2" />
          <div className="p-3 bg-gray-50 rounded-lg">
            <h3 className="font-medium mb-2">事件详情: {selectedEmergency.title}</h3>
            <div className="space-y-2 text-sm">
              <p><span className="font-medium">位置:</span> {selectedEmergency.location.name} ({selectedEmergency.location.floor})</p>
              <p><span className="font-medium">描述:</span> {selectedEmergency.description}</p>
              <p><span className="font-medium">开始时间:</span> {formatTime(selectedEmergency.startTime)}</p>
              <p><span className="font-medium">状态:</span> {getStatusBadge(selectedEmergency.status)}</p>
              
              {selectedEmergency.updates.length > 0 && (
                <>
                  <p className="font-medium mt-2">事件进展:</p>
                  <div className="pl-2 border-l-2 border-gray-300 space-y-1">
                    {selectedEmergency.updates.map(update => (
                      <div key={update.id} className="text-xs">
                        <span className="text-gray-500">{formatTime(update.timestamp)}</span>
                        <span className="ml-2">{update.content}</span>
                        {update.statusChange && (
                          <span className="ml-2 text-xs">
                            {getStatusBadge(update.statusChange)}
                          </span>
                        )}
                      </div>
                    ))}
                  </div>
                </>
              )}
            </div>
          </div>
        </div>
      )}
    </div>
  )
}

export default EmergencyPanel